<template>
  <div class="ques-cate-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="70%">
      <el-form ref="quesCateDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="分类" prop="cateId">
              <el-tree-select
                  v-model="state.ruleForm.cateId"
                  :data="state.cateData"
                  node-key="id"
                  clearable
                  check-strictly
                  placeholder="请选择分类"
                  :props="{ children: 'children',label:'label'}"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="题干" prop="quesInfo">
              <el-input v-model="state.ruleForm.quesInfo" type="textarea" placeholder="请输入题干" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="试题分数" prop="score">
              <el-input-number :min="0" v-model="state.ruleForm.score" placeholder="请输入分数"
                               clearable></el-input-number>
            </el-form-item>
          </el-col>
          <!--          单选题选项-->
          <template v-if="state.ruleForm.quesType === 1">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item prop="optionList" label="选项">
                <el-button type="primary" @click="onAddQuesOption">添加选项</el-button>
                <el-table :data="state.ruleForm.optionList" style="width: 100%">
                  <el-table-column prop="date" label="是否答案" width="90">
                    <template #default="scope">
                      <el-checkbox v-model="scope.row.isRight" @change="handleOptionIsRightChange(scope.$index)"
                                   class="mr10"></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="选项">
                    <template #default="scope">
                      <el-input style="margin-right: 10px" v-model="scope.row.content" placeholder="请输入选项"
                                clearable></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="答案解析">
                    <template #default="scope">
                      <el-input style="margin-right: 10px" v-model="scope.row.analysis" placeholder="请输入答案解析"
                                clearable></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="操作" width="90px">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="onDelQuesOption(scope.$index)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </template>
          <!--          单选题选项  end   -->
          <!--          多选题选项  start   -->
          <template v-if="state.ruleForm.quesType === 2">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item prop="optionList" label="选项">
                <el-button type="primary" @click="onAddQuesOption">添加选项</el-button>
                <el-table :data="state.ruleForm.optionList" style="width: 100%">
                  <el-table-column prop="date" label="是否答案" width="90">
                    <template #default="scope">
                      <el-checkbox v-model="scope.row.isRight" class="mr10"></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="选项">
                    <template #default="scope">
                      <el-input style="margin-right: 10px" v-model="scope.row.content" placeholder="请输入选项"
                                clearable></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="答案解析">
                    <template #default="scope">
                      <el-input style="margin-right: 10px" v-model="scope.row.analysis" placeholder="请输入答案解析"
                                clearable></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="操作" width="90">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="onDelQuesOption(scope.$index)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </template>
          <!--          多选题选项 end  -->
          <!--          判断题选项  start   -->
          <template v-if="state.ruleForm.quesType === 3">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item prop="optionList" label="选项">
                <el-table :data="state.ruleForm.optionList" style="width: 100%">
                  <el-table-column prop="date" label="是否答案" width="90">
                    <template #default="scope">
                      <el-checkbox v-model="scope.row.isRight" @change="handleOptionIsRightChange(scope.$index)"
                                   class="mr10"></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="选项">
                    <template #default="scope">
                      <el-input style="margin-right: 10px" v-model="scope.row.content" placeholder="请输入选项"
                                clearable></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="答案解析">
                    <template #default="scope">
                      <el-input style="margin-right: 10px" v-model="scope.row.analysis" placeholder="请输入答案解析"
                                clearable></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="操作" width="90">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="onDelQuesOption(scope.$index)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </template>
          <!--          判断选项 end  -->
          <!--          填空题  start   -->
          <template v-if="state.ruleForm.quesType === 4">

            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item prop="optionList" label="选项">
                <el-table :data="state.ruleForm.optionList" style="width: 100%" fit>
                  <el-table-column prop="name" label="选项">
                    <template #default="scope">
                      <el-input style="margin-right: 10px" v-model="scope.row.content" placeholder="请输入选项"
                                clearable></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="操作" width="90">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="onDelQuesOption(scope.$index)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="答案是否乱序">
                <el-radio-group v-model="state.ruleForm.answerDisorder">
                  <el-radio-button label="true">是</el-radio-button>
                  <el-radio-button label="false">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </template>
          <!--          多填空题选项 end  -->

          <!--          问答题  start   -->
          <template v-if="state.ruleForm.quesType === 5">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item :label="`答案`" prop="answer">
                <el-input style="margin-right: 10px" v-model="state.ruleForm.answer" type="textarea"
                          placeholder="请输入答案" clearable></el-input>
              </el-form-item>
            </el-col>
          </template>
          <!--          问答题 end  -->

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="难度" prop="quesLevel">
              <el-radio-group v-model="state.ruleForm.quesLevel">
                <el-radio-button :label="1">简单</el-radio-button>
                <el-radio-button :label="2">普通</el-radio-button>
                <el-radio-button :label="3">困难</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="排序" prop="analysis">
              <el-input v-model="state.ruleForm.analysis" type="textarea" placeholder="请输入解析内容"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(quesCateDialogFormRef)" size="default">{{
              state.dialog.submitTxt
            }}</el-button>
				</span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="quesCateDialog">
import {nextTick, reactive, ref} from 'vue';
import {useQuesApi} from "/@/api/ques";
import {useSystemApi} from "/@/api/system";


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入api
const quesApi = useQuesApi();
const systemApi = useSystemApi();

// 定义变量内容
const quesCateDialogFormRef = ref();

const state = reactive({
  cateData: [],
  ruleForm: {
    id: '',
    quesInfo: '',
    cateId: '', //
    optionList: [],
    answer: '', //
    quesLevel: 1,
    quesType: 1,
    analysis: '',
    score: 1,
    answerDisorder: false,
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
});


const checkOptions = (rule, value, callback) => {
  if (state.ruleForm.quesType === 1 || state.ruleForm.quesType === 2) {

    let isRightCount = 0
    state.ruleForm.optionList.forEach(item => {
      if (!item.content.trim()) {
        callback(new Error('请输入选项内容'))
        return
      }
      if (item.isRight) {
        isRightCount++
      }
    })


    if (state.ruleForm.quesType === 2 && isRightCount <= 1) {
      callback(new Error('请至少选择两个答案'))
    } else if (isRightCount <= 0) {
      callback(new Error('请选择答案'))
    }


    callback()
  } else {
    callback()
  }

}

const checkFillBlacks = (rule, value, callback) => {
  if (state.ruleForm.quesType === 4) {
    for (let i = 0; i < value.length; i++) {
      if (!value[i] || value[i].trim().length === 0) {
        callback(new Error('答案不能为空'))
        return
      }
    }

    callback()
  } else {
    callback()
  }

}


const optionKey = ref(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"])

const rules = reactive({
  cateId: [
    {required: true, message: '请选择分类', trigger: 'change'},
  ],
  quesInfo: [
    {required: true, message: '请输入题干', trigger: 'blur'},
  ],
  answer: [
    {required: true, message: '请输入答案', trigger: 'change'},
  ],
  optionList: [
    {validator: checkOptions, trigger: 'blur'},
  ],
})

// 打开弹窗
const openDialog = (type, row) => {

  getCateData()

  state.dialog.type = type;
  if (type === 'edit') {
    state.dialog.title = '修改试题';
    state.dialog.submitTxt = '修 改';

    quesApi.bankInfo(row.id).then(res => {
      state.ruleForm = res.data
    })

  } else {
    state.dialog.title = '新增试题';
    state.dialog.submitTxt = '新 增';

    state.ruleForm.quesType = row.quesType
    if (row.quesType === 1) {
      state.ruleForm.optionList = [
        {
          tag: "A",
          content: "",
          isRight: false,
          analysis: '',
        },
        {
          tag: "B",
          content: "",
          isRight: false,
          analysis: '',
        }
      ]
    } else if (row.quesType === 2) {
      state.ruleForm.optionList = [
        {
          tag: "A",
          content: "",
          isRight: false,
          analysis: '',
        },
        {
          tag: "B",
          content: "",
          isRight: false,
          analysis: '',
        }
      ]
    } else if (row.quesType === 3) {
      state.ruleForm.optionList = [
        {
          tag: "A",
          content: "正确",
          isRight: true,
          analysis: '',
        },
        {
          tag: "B",
          content: "错误",
          isRight: false,
          analysis: '',
        }
      ]
    } else if (row.quesType === 4) {
      state.ruleForm.optionList = [
        {
          tag: "",
          content: "",
          isRight: false,
          analysis: '',
        },
        {
          tag: "",
          content: "",
          isRight: false,
          analysis: '',
        }
      ]
    }

    // 清空表单，此项需加表单验证才能使用
    nextTick(() => {
      quesCateDialogFormRef.value.resetFields();
    });
  }
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

// 获取分类
const getCateData = () => {
  quesApi.cateTree().then(res => {
    state.cateData = res.data.children
  })
}

// 提交
const onSubmit = async (formEl) => {

  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (state.dialog.type === 'edit') {
        onUpdate()
      } else {
        onAdd()
      }
    }
  })

};

// 新增
const onAdd = () => {

  quesApi.bankAdd({
    "cateId": state.ruleForm.cateId,
    "quesInfo": state.ruleForm.quesInfo,
    "optionList": state.ruleForm.optionList,
    "quesLevel": state.ruleForm.quesLevel,
    "quesType": state.ruleForm.quesType,
    "analysis": state.ruleForm.analysis,
    "score": state.ruleForm.score,
    "answerDisorder": state.ruleForm.answerDisorder,
  }).then(() => {
    closeDialog();
    emit('refresh');
  })
}

// 更新
const onUpdate = () => {
  quesApi.bankUpdate({
    "id": state.ruleForm.id,
    "cateId": state.ruleForm.cateId,
    "quesInfo": state.ruleForm.quesInfo,
    "optionList": state.ruleForm.optionList,
    "quesLevel": state.ruleForm.quesLevel,
    "quesType": state.ruleForm.quesType,
    "analysis": state.ruleForm.analysis,
    "score": state.ruleForm.score,
    "answerDisorder": state.ruleForm.answerDisorder,
  }).then(() => {
    closeDialog();
    emit('refresh');
  })
}

// 添加单选题选项
const onAddQuesOption = () => {
  if (state.ruleForm.optionList.length >= optionKey.value.length) {
    return
  }
  state.ruleForm.optionList.push({
    tag: optionKey.value[state.ruleForm.optionList.length],
    content: "",
    isRight: false,
    analysis: ''
  })
}

const onDelQuesOption = (inx) => {
  state.ruleForm.optionList.splice(inx, 1)
}



const handleOptionIsRightChange = (inx) => {
  if (state.ruleForm.quesType === 1 || state.ruleForm.quesType === 3) {
    for (let i = 0; i < state.ruleForm.optionList.length; i++) {
      state.ruleForm.optionList[i].isRight = i === inx
    }
  }
}


// 暴露变量
defineExpose({
  openDialog,
});

</script>

<style scoped>

</style>